package NetWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class MyTCPClient {
    //用来链接服务器
    private Socket clientSocket = null;
    //构造方法来建立链接
    public MyTCPClient(String ip,int port) throws IOException {
        clientSocket = new Socket(ip,port);
        System.out.println("客户端链接成功");
    }
    //启动方法
    public void start() {
        //这个scanner用来获取用户的输入
        Scanner in = new Scanner(System.in);
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            //将字节流封住成字符串
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scanner = new Scanner(inputStream);
            while(true) {
                System.out.println("->");
                String request = in.next();
                //发送请求
                printWriter.println(request);
                printWriter.flush();
                //接收响应
                String respond = scanner.next();
                //显示
                System.out.printf("[req:%s,resp:%s]\n",request,respond);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        MyTCPClient myTCPClient = new MyTCPClient("127.0.0.1",6666);
        myTCPClient.start();
    }
}
